package io.renren.modules.app.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.app.service.UserService;
import io.renren.modules.sys.entity.CodeEntity;
import io.renren.modules.sys.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangyi
 * @mail 794651397@qq.com
 * @createdate 2018/3/22 11:49
 **/
@Api(description = "忘记密码")
@RestController
@RequestMapping("/app")
public class ApiForgetPasswordController {
    @Autowired
    private UserService userService;

    /**
     * 忘记密码
     * @author wangyi
     * @createdate 2018/3/22 11:44
     **/
    @ApiOperation("忘记密码")
    @PostMapping("forgetPassword")
    public R forgetPassword(String mobile, String password, String SMSCode){
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(SMSCode, "短信验证码不能为空");
        UserEntity userEntity=userService.queryByMobile(mobile);
        if(userEntity==null){
            throw new RRException("此手机号还未注册账号,请先注册");
        }
        CodeEntity codeEntity=userService.queryCodeByMobile(mobile);
        if(codeEntity==null){
            throw new RRException("请先获取验证码");
        }
        Long expire=codeEntity.getExpire();
        String code=codeEntity.getCode();
        if(DateUtils.getTime()>expire){
            throw new RRException("验证码已过期");
        }
        if(!SMSCode.equals(code)){
            throw new RRException("验证码错误");
        }
        Long userId=userEntity.getUserId();
        userService.forgetPassword(userId,password);

        return R.ok();
    }

}
